import { defineStore } from "pinia";
import { ref, computed } from 'vue';
import { ElMessage } from "element-plus";

export const useLanguageStore = defineStore("language", () => {
  // 默认语言优先从本地存储获取
  const localLang = JSON.parse(localStorage.getItem("pinia-language"))
  const currentLang = ref(localLang || 'zh')

  //语言包缓存
  const langPacks = ref({
    zh: null,
    en: null
  })

  // 动态加载语言包
  const loadLanguagePack = async (lang) => {
    if (!langPacks.value) {
      langPacks.value = {}
    }
    if (!langPacks.value[lang]) {
      try {
        const module = await import(`@/assets/language/${lang}.json`)
        langPacks.value[lang] = module.default
      } catch (e) {
        ElMessage.error("切换语言错误！")
        // 回退到默认语言
        if (lang !== 'zh') {
          return loadLanguagePack('zh')
        }
      }
    }
    return langPacks.value[lang]
  }

  // 获取当前语言文本
  const t = computed(() => {
    return (key) => {
      const pack = langPacks.value[currentLang.value]
      return pack?.[key] || key
    }
  })

  // 切换语言
  const switchLanguage = async (lang) => {
    if (lang !== currentLang.value) {
      await loadLanguagePack(lang)
      currentLang.value = lang
    }
  }

  // 初始化默认语言
  const init = async () => {
    await loadLanguagePack(currentLang.value)
  }

  return {
    currentLang, t, switchLanguage, init
  }

}, {
  persist: true
})